#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

using namespace TcpServerModule;

using http_handler_t = std::function<void(HttpRequest &,HttpResponse &)>;

class HttpServer
{
    public:
    HttpServer(int port)
    :_tsvr(std::make_unique<TcpServer>(port))
    {}
    void Resgiter(std::string funcname,http_handler_t func)
    {
        _route[funcname] = func;

    }
    bool SafeCheck(std::string &service)
    {
        auto iter = _route.find(service);
        return iter != _route.end();
    }
    void Start()
    {
        _tsvr->InitServer([this](SockPtr sockfd, InetAddr client){return this->HandlerHttpRequest(sockfd,client);});
        _tsvr->Loop();
    }
    bool HandlerHttpRequest(SockPtr sockfd, InetAddr client)
    {
        LOG(LogLevel::DEBUG) << "HttpServer: get a new client: " << sockfd->Fd() << " addr info: " << client.Addr();
        std::string http_request;
        sockfd->Recv(&http_request);
        HttpRequest req;
        req.Deserialize(http_request);
        HttpResponse resp;
        if(req.IsHasArgs())
        {
            std::cout << "------IsHasArgs()" << std::endl;
            std::string service = req.Path();
            if(SafeCheck(service))
            _route[req.Path()](req,resp);
            else
            resp.Build(req);
        }
        else{
            std::cout << "-----Non IsHasArgs()" << std::endl;
            resp.Build(req);
        }
        std::string resp_str;
        resp.Serialize(&resp_str);
        sockfd->Send(resp_str);
        return true;

    }
    ~HttpServer(){}
    private:
    std::unique_ptr<TcpServer> _tsvr;
    std::unordered_map<std::string, http_handler_t> _route;
};